import { BASE_URL } from '../../../http/config';
Page({
  data: {
    questions: [], // 题目列表
    currentIndex: 0, // 当前题目索引
    answers: {}, // {questionId: {optionId, score, label}}
    loading: true,
    id: '',
    optionLabels: ['A', 'B', 'C', 'D'],
    optionScores: [6, 5, 4, 3],
    selectedOptionId: null, // 当前题目已选optionId
  },

  onLoad(options) {
    const id = options.id;
    console.log('TestWorkIng onLoad options:', options);
    console.log('TestWorkIng onLoad id:', id);
    this.setData({ id });
    this.loadQuestions(id);
  },

  // 拉取题目
  loadQuestions(id) {
    wx.showLoading({ title: '加载题目中...' });
    wx.request({
      url: `${BASE_URL}/psychologyTest/selectAllTitleAndOptions/${id}`,
      success: (res) => {
        const questions = res.data.data[0];
        let selectedOptionId = null;
        if (questions && questions.psychologyTestTitleList && questions.psychologyTestTitleList.length > 0) {
          const firstQuestion = questions.psychologyTestTitleList[0];
          selectedOptionId = this.data.answers[firstQuestion.id]?.optionId || null;
        }
        // 将测试ID保存到questions对象中
        if (questions) {
          questions.psychologyTestId = parseInt(id);
        }
        this.setData({
          questions,
          loading: false,
          selectedOptionId
        });
        if (!questions || !questions.psychologyTestTitleList || questions.psychologyTestTitleList.length === 0) {
          wx.showModal({
            title: '提示',
            content: '暂时无题目',
            showCancel: false,
            success: () => wx.navigateBack()
          });
        }
      },
      fail: () => {
        wx.showToast({ title: '加载失败', icon: 'none' });
        this.setData({ loading: false });
      },
      complete: () => wx.hideLoading()
    });
  },

  // 选项选择
  handleOptionSelect(e) {
    const { id: optionId, index: optionIndex } = e.currentTarget.dataset;
    const { currentIndex, questions, optionLabels, optionScores } = this.data;
    const currentQuestion = questions.psychologyTestTitleList[currentIndex];
    const score = optionScores[optionIndex];
    const label = optionLabels[optionIndex];
    this.setData({
      [`answers[${currentQuestion.id}]`]: { optionId, score, label },
      selectedOptionId: optionId
    });
    // 自动跳到下一题
    setTimeout(() => {
      if (currentIndex < questions.psychologyTestTitleList.length - 1) {
        const nextIndex = currentIndex + 1;
        const nextQuestion = questions.psychologyTestTitleList[nextIndex];
        this.setData({
          currentIndex: nextIndex,
          selectedOptionId: this.data.answers[nextQuestion.id]?.optionId || null
        });
      } else {
        // 题目全部答完，统计分数并跳转
        this.submitAnswers();
      }
    }, 200);
  },

  // 上一题
  prevQuestion() {
    if (this.data.currentIndex > 0) {
      const prevIndex = this.data.currentIndex - 1;
      const prevQuestion = this.data.questions.psychologyTestTitleList[prevIndex];
      this.setData({
        currentIndex: prevIndex,
        selectedOptionId: this.data.answers[prevQuestion.id]?.optionId || null
      });
    }
  },
  // 下一题
  nextQuestion() {
    if (this.data.currentIndex < this.data.questions.psychologyTestTitleList.length - 1) {
      const nextIndex = this.data.currentIndex + 1;
      const nextQuestion = this.data.questions.psychologyTestTitleList[nextIndex];
      this.setData({
        currentIndex: nextIndex,
        selectedOptionId: this.data.answers[nextQuestion.id]?.optionId || null
      });
    }
  },

  // 统计分数并跳转
  submitAnswers() {
    const { answers, questions, id } = this.data;
    const totalScore = Object.values(answers).reduce((sum, ans) => sum + ans.score, 0);
    
    // 调试信息
    console.log('当前页面id:', id);
    console.log('questions数据:', questions);
    
    // 获取psychology_test_id，优先使用页面id，如果没有则从questions中获取
    let psychologyTestId = parseInt(id);
    if (!psychologyTestId && questions && questions.psychologyTestId) {
      psychologyTestId = questions.psychologyTestId;
    }
    if (!psychologyTestId && questions && questions.id) {
      psychologyTestId = parseInt(questions.id);
    }
    
    console.log('最终使用的psychology_test_id:', psychologyTestId);
    
    // 根据分数生成content内容
    let content = '';
    if (totalScore >= 0 && totalScore <= 30) {
      content = "您的心理状态非常不健康，可能需要及时调整。";
    } else if (totalScore > 30 && totalScore <= 60) {
      content = "您近期可能有些压力，需要适当放松。";
    } else if (totalScore > 60 && totalScore <= 90) {
      content = "您的心理状态良好，继续保持。";
    } else if (totalScore > 90 && totalScore <= 100) {
      content = "您的心理状态极佳，继续保持积极心态。";
    }
    
    // 获取用户信息
    const userInfo = wx.getStorageSync('userInfo');
    if (!userInfo || !userInfo.id) {
      wx.showToast({
        title: '用户信息获取失败',
        icon: 'none'
      });
      return;
    }
    
    // 准备提交的数据
    const submitData = {
      score: totalScore,
      content: content,
      psychologyTestId: psychologyTestId,
      userId: userInfo.id,
      testTime: new Date().toISOString().slice(0, 19).replace('T', ' '), // 格式化为 YYYY-MM-DD HH:mm:ss
      del: 0
    };
    
    // 调试信息
    console.log('准备提交的数据:', submitData);
    
    // 调用接口保存数据
    wx.request({
      url: `${BASE_URL}/psychologyTestResult/add`,
      method: 'POST',
      data: submitData,
      header: {
        'content-type': 'application/json'
      },
      success: (res) => {
        console.log('测试结果保存成功:', res);
        // 保存成功后跳转到结果页面
        wx.navigateTo({
          url: `/index/pages/ResultTest/ResultTest?score=${totalScore}`
        });
      },
      fail: (err) => {
        console.error('测试结果保存失败:', err);
        wx.showToast({
          title: '结果保存失败',
          icon: 'none'
        });
        // 即使保存失败也跳转到结果页面
        wx.navigateTo({
          url: `/index/pages/ResultTest/ResultTest?score=${totalScore}`
        });
      }
    });
  },
});